package common.concurrency.baeldung.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * join和get区别
 */
public class JoinVsGet {
    public static void jointest() {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> 31);
        Integer join = completableFuture.join();
        System.out.println("join result" + join);

        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("simulated join exception");
        });
        try {
            completableFuture2.join();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    public static void gettest() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);

        // 阻塞等待异步任务的结果
        Integer result = future.get();
        System.out.println("Result: " + result); // 输出: Result: 42

        // 如果抛出异常，可以捕获
        CompletableFuture<Integer> faultyFuture = CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("Some error");
        });

        try {
            faultyFuture.get(); // 会抛出 ExecutionException
        } catch (ExecutionException e) {
            System.out.println("Exception occurred: " + e.getCause()); // 输出: Some error
        }

    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //jointest();
        gettest();
    }
}
